/*
 * @Author: 史许荣
 * @Date: 2022-07-29 12:53:37
 * @LastEditors: 史许荣
 * @LastEditTime: 2022-08-04 14:52:23
 * @Description: file content
 * @FilePath: \react-three-fiber-new\src\Particles.js
 */
import * as THREE from 'three'
import React, { useRef, useMemo } from 'react'
import { useFrame, useThree } from '@react-three/fiber'
import './styles.css'
import { PointMaterial } from '@react-three/drei'
export default function Particles({ count }) {
  const mesh = useRef()
  const dummy = useMemo(() => new THREE.Object3D(), [])
  const particles = useMemo(() => {
    const temp = []
    for (let i = -50; i <= 50; i+=4) {
      for (let j = -50; j <= 50; j+=4) {
        const xFactor = i
        const yFactor = -1
        const zFactor = j
        temp.push({  xFactor, yFactor, zFactor})
      }
      
    }
    return temp
  }, [])
  const particles2 = useMemo(() => {
    const temp = []
    for (let i = 0; i <= 2000; i+=1) {
      const xFactor = -25 + Math.random() * 50
      const yFactor = -5
      const zFactor = -25 + Math.random() * 50
      const xMove= (Math.floor(Math.random() * 10) - 5)/400;
      const yMove= (Math.floor(Math.random() * 8) )/100;
      const zMove= (Math.floor(Math.random() * 10) - 5)/400;
      temp.push({  xFactor, yFactor, zFactor,xMove,yMove,zMove})
    }
    return temp
  }, [])
  useFrame((state) => {
    particles.forEach((particle, i) => {
      let { xFactor, yFactor, zFactor } = particle
      dummy.position.set(
          xFactor,
          yFactor,
          zFactor
      )
      dummy.updateMatrix()
      dummy.quaternion.copy(state.camera.quaternion)
      mesh.current.setMatrixAt(i, dummy.matrix)
    })
    
    mesh.current.instanceMatrix.needsUpdate = true

    

    particles2.forEach((particle, i) => {
      let {  xFactor, yFactor, zFactor,xMove,zMove,yMove } = particle
     
      if(particle.yFactor>=15){
        particle.xFactor = -50 + Math.random() * 100
        particle.yFactor = -5
        particle.zFactor = -50 + Math.random() * 100
      }else{
        particle.xFactor+=xMove;
        particle.yFactor+=yMove;
        particle.zFactor+=zMove;
      }
      dummy.position.set(
        xFactor,
        yFactor,
        zFactor
      )
      
      dummy.updateMatrix()
      dummy.quaternion.copy(state.camera.quaternion)
      mesh.current.setMatrixAt(particles.length+i, dummy.matrix)
      
    })
  })
  return (
    <group>
      <instancedMesh ref={mesh} args={[null, null, count]}>
        <circleGeometry args={[0.03, 64, 64]} />
        <PointMaterial color={'#00E3FF'}/>
      </instancedMesh>
    </group>
  )
}
